package com.demo.util.encryption;

import org.apache.commons.codec.binary.Hex;
import org.springframework.util.Assert;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
 
public class AESHelper {
 
	private static String password = "xiehuaxin";
	
	public static void main(String[] args) throws Exception {

		String encode = encode(password);
		System.out.println(encode);
		String decode = decode(encode);
		System.out.println(decode);

	}

	public static String encode(String value) throws Exception {
		Assert.notNull(value,"加密内容不能为null");
//1.生成KEY
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(new SecureRandom("aa".getBytes()));
		SecretKey secretKey = keyGenerator.generateKey();
		byte[] byteKey = secretKey.getEncoded();

		//2.转换KEY
		Key key = new SecretKeySpec(byteKey,"AES");

		//3.加密
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] result = cipher.doFinal(password.getBytes());
		System.out.println("加密后：" + Hex.encodeHexString(result));
		return Hex.encodeHexString(result);
	}


	public static String decode(String value) throws Exception {
		//1.生成KEY
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(new SecureRandom("aa".getBytes()));
		SecretKey secretKey = keyGenerator.generateKey();
		byte[] byteKey = secretKey.getEncoded();

		//2.转换KEY
		Key key = new SecretKeySpec(byteKey,"AES");

		//3.加密
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] result = cipher.doFinal(value.getBytes());
		return new String(result);
	}

}